const Router = require("koa-router");
const { getUsers, pageUserList, signup, login } = require("../controller/user");
const newsCtrl = require("../controller/news");
const multer = require("@koa/multer");
// const koaBody = require("koa-body");
const path = require("path");
const fs = require("fs");

const router = new Router();

// 获取用户列表 请求方式为get
router.get("/user/list", getUsers);
// 用户注册，post
router.post("/signup", signup);
// 用户登录，post
router.post("/login", login);

router.post("/news/add", newsCtrl.add);

router.post("/news/edit", newsCtrl.edit);

router.post("/news/del", newsCtrl.del);

router.post("/news/detail", newsCtrl.detail);

router.post("/news/list", newsCtrl.pageList);

router.get("/news/idList", newsCtrl.idList);

// 确保 `uploads` 目录存在
const uploadDir = "public/uploads";
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir);
}

// 配置存储方式
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir); // 指定上传目录
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname)); // 时间戳 + 原始扩展名
  },
});

const upload = multer({ storage });

// 处理单个文件上传
router.post("/upload", upload.single("file"), async (ctx) => {
  if (!ctx.file) {
    ctx.status = 400;
    ctx.body = { error: 1, message: "没有上传文件" };
    return;
  }
  // ctx.body = { error: 0, data: {message: "文件上传成功", url: 'http://localhost:8089/'+ctx.file.filename }};
  ctx.body = { error: 0, data: {message: "文件上传成功", url: ctx.file.filename }};
});



module.exports = router;
